<template>
  <div class="cookbook">
    <el-date-picker
        clearable
        v-model="eatTime"
        type="date"
        value-format="yyyy-MM-dd"
        placeholder="选择用餐日期">
    </el-date-picker>
    <el-select clearable style="margin: 0 20px;" v-model="cookbookType" placeholder="请选择用餐类型">
      <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value">
      </el-option>
    </el-select>
    <el-button @click="searchCookbook" icon="el-icon-search" type="primary">搜索</el-button>
    <el-button @click="addCookbook" icon="el-icon-plus" type="primary">添加菜谱</el-button>
    <el-button @click="deleteCookbookBatch" icon="el-icon-delete" type="danger" :disabled="cookbookIds.length === 0">批量删除</el-button>
    <el-table v-loading="loading" :data="tableData" class="table" @selection-change="changeSelection">
      <el-table-column
          type="expand"
          width="50">
        <template slot-scope="scope">
          <el-table :data="scope.row.foodVos" border>
            <el-table-column
                prop="id"
                label="菜品ID"
                width="100">
            </el-table-column>
            <el-table-column
                prop="title"
                label="菜品名称"
                width="150">
            </el-table-column>
            <el-table-column
                prop="description"
                label="菜品描述"
                width="200">
            </el-table-column>
            <el-table-column
                prop="price"
                label="菜品价格（元）"
                width="150">
            </el-table-column>
            <el-table-column
                prop="stock"
                label="菜品库存（份）"
                width="150">
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column
          prop="eatTime"
          label="用餐日期"
          width="300">
      </el-table-column>
      <el-table-column
          prop="endTime"
          label="订餐截止时间"
          width="300">
      </el-table-column>
      <el-table-column
          prop="maxNum"
          label="菜品预订上限"
          width="300">
      </el-table-column>
      <el-table-column
          prop="cookbookType"
          label="用餐类型"
          width="200">
        <template slot-scope="scope">
          {{scope.row.cookbookType === 1 ? '午餐' : '晚餐'}}
        </template>
      </el-table-column>
      <el-table-column
          fixed="right"
          label="操作"
          width="300">
        <template slot-scope="scope">
          <el-button @click="editCookbook(scope.row)" size="small" type="primary" icon="el-icon-edit">编辑</el-button>
          <el-popconfirm class="confirm" title="确定删除？" @confirm="deleteCookbook(scope.row)">
            <el-button  size="small" slot="reference" type="danger" icon="el-icon-delete">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        @current-change="changePage"
        class="page"
        background
        layout="prev, pager, next"
        :page-size="pageSize"
        :total="total">
    </el-pagination>
    <el-dialog :title="cookbookFormTitle" :visible="showCookbookForm"  @close="closeCookbookForm">
      <el-form :model="cookbookForm" label-width="120px" ref="cookbookForm" :rules="cookbookRules" >
        <el-form-item prop="eatTime" label="用餐日期">
          <el-date-picker
              clearable
              v-model="cookbookForm.eatTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择用餐日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item prop="endTime" label="订餐截止时间">
          <el-date-picker
              v-model="cookbookForm.endTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择订餐截止时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item prop="maxNum" label="菜谱预订上限">
          <el-input v-model="cookbookForm.maxNum" style="width: 220px">
            <template slot="append">份</template>
          </el-input>
        </el-form-item>
        <el-form-item prop="cookbookType" label="用餐类型">
          <el-select v-model="cookbookForm.cookbookType" placeholder="请选择用餐类型">
            <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="cookbookFoodIds" label="菜品">
          <el-transfer @change="handleChange" v-model="cookbookForm.cookbookFoodIds" :data="foodList" :props="{key: 'id', label: 'title'}" :titles="['全部菜品', '已选菜品']"></el-transfer>
        </el-form-item>
        <el-form-item prop="foodStockList" label="设置库存" v-show="cookbookForm.foodStockList.length > 0">
          <div class="stock" v-for="item in cookbookForm.foodStockList" :key="item.id">
            <span>{{item.title}}</span>
            <el-input-number v-model="item.stockNum" :min="0"></el-input-number>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="closeCookbookForm">取消</el-button>
        <el-button type="primary" @click="submitCookbookForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Cookbook",
  data () {
    return {
      loading: false,
      tableData: [],
      eatTime: '',
      pageNum: 1,
      pageSize: 10,
      total: 0,
      cookbookType: '',
      options: [{
        value: 1,
        label: '午餐'
      }, {
        value: 2,
        label: '晚餐'
      }],
      cookbookIds: [],
      foodList: [],
      showCookbookForm: false,
      cookbookFormTitle: '',
      cookbookForm: {
        eatTime: '',
        endTime: '',
        maxNum: '',
        cookbookType: '',
        cookbookFoodIds: [],
        foodStockList: []
      },
      cookbookRules: {
        eatTime: [{ required: true, message: '必填', trigger: 'blur' }],
        endTime: [{ required: true, message: '必填', trigger: 'blur' }],
        maxNum: [{ required: true, message: '必填', trigger: 'blur' }],
        cookbookType: [{ required: true, message: '必填', trigger: 'blur' }],
        cookbookFoodIds: [{ required: true, message: '必填', trigger: 'blur' }],
        foodStockList: [{ required: true, message: '必填', trigger: 'blur' }]
      }
    }
  },
  methods:{
    // getFoodList (row) {
    //   const foodVos = row.foodVos
    //   return foodVos.map(foodVo => foodVo.title).join()
    // },
    handleChange(value, direction, movedKeys) {
      const movedStockList = this.foodList.map(food => {
        return {
          id: food.id,
          title: food.title,
          stockNum: 0
        }
      }).filter(foodStock => movedKeys.indexOf(foodStock.id) > -1)
      switch (direction) {
        case 'right':
          this.cookbookForm.foodStockList = this.cookbookForm.foodStockList.concat(movedStockList)
          break
        case 'left':
          for (const movedKey of movedKeys) {
            let index = this.cookbookForm.foodStockList.findIndex(foodStock => foodStock.id === movedKey)
            this.cookbookForm.foodStockList.splice(index, 1)
          }
          break
      }
    },
    loadFoodList () {
      this.$axios.get('/cookbook/food').then(res => {
        if (res.code === 200) {
          this.foodList = res.data
        }
      })
    },
    closeCookbookForm () {
      this.showCookbookForm = false
      this.cookbookForm = {
        eatTime: '',
        endTime: '',
        maxNum: '',
        cookbookType: '',
        cookbookFoodIds: [],
        foodStockList: []
      }
    },
    submitCookbookForm () {
      const cookbookBo = this.cookbookForm
      if (this.cookbookForm.id) {
        this.$axios.put(`/cookbook/${this.cookbookForm.id}`, cookbookBo).then(res => {
          if (res.code === 200) {
            this.closeCookbookForm()
            this.loadTableData()
          }
        })
      } else {
        this.$axios.post('/cookbook', cookbookBo).then(res => {
          if (res.code === 200) {
            this.closeCookbookForm()
            this.loadTableData()
          }
        })
      }
    },
    loadTableData () {
      this.loading = true
      this.$axios.get(`/cookbook?eatTime=${this.eatTime}&cookbookType=${this.cookbookType}&pageNum=${this.pageNum}&pageSize=${this.pageSize}`).then(res => {
        this.loading = false
        if (res.code === 200) {
          this.tableData = res.data.records
          this.total = res.data.total
        }
      })
    },
    changeSelection (rows) {
      this.cookbookIds = []
      for (const row of rows) {
        this.cookbookIds.push(row.id)
      }
    },
    searchCookbook () {
      this.pageNum = 1
      this.loadTableData()
    },
    addCookbook () {
      this.cookbookFormTitle = '添加菜谱'
      this.showCookbookForm = true
      this.loadFoodList()
    },
    editCookbook (row) {
      this.cookbookForm = {
        id: row.id,
        eatTime: row.eatTime,
        endTime: row.endTime,
        maxNum: row.maxNum,
        cookbookType: row.cookbookType,
        cookbookFoodIds: row.foodVos.map(foodVo => foodVo.id),
        foodStockList: row.foodVos.map(foodVo => {
          return {
            id: foodVo.id,
            title: foodVo.title,
            stockNum: foodVo.stock
          }
        })
      }
      this.cookbookFormTitle = '编辑菜谱'
      this.showCookbookForm = true
      this.loadFoodList()
    },
    deleteCookbook (row) {
      this.$axios.delete(`/cookbook/${row.id}`).then(res => {
        if (res.code === 200) {
          this.pageNum = 1
          this.loadTableData()
        }
      })
    },
    deleteCookbookBatch () {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.delete('/cookbook/batch', {
          data: this.cookbookIds
        }).then(res => {
          if (res.code === 200) {
            this.pageNum = 1
            this.loadTableData()
          }
        })
      })
    },
    changePage (pageNum) {
      this.pageNum = pageNum
      this.loadTableData()
    }
  },
  watch: {
  },
  mounted() {
    this.loadTableData()
  }
}
</script>

<style lang="scss" scoped>
  .cookbook {
    width: 100%;
    height: 100%;
    .table {
      width: 100%;
      margin-top: 20px;
    }
    .confirm {
      margin-left: 20px;
    }
    .page {
      margin: 20px 0;
    }
    .stock {
      width: 50%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      box-sizing: border-box;
      padding: 0 20px 20px 0;
    }
  }
</style>